#include <iostream>
#include <string>
#include <cstdlib>
#include <mysql/mysql.h>

#define HOST "127.0.0.1"
#define USER "root"
#define PWD "mzx15378261830"
#define DB_NAME "gobang"
#define PORT 3306

int main()
{
    //1.初始化mysql句柄
    MYSQL* mysql = mysql_init(nullptr);
    if (mysql == nullptr)
    {
        std::cout << "mysql init failed" << std::endl;
        exit(-1);
    }
    //2.连接服务器
    if (mysql_real_connect(mysql, HOST, USER, PWD, DB_NAME, PORT, nullptr, 0) == nullptr)
    {
        std::cout << "connect mysql server failed, " << mysql_error(mysql) << std::endl;
        mysql_close(mysql);
        exit(-1);
    }
    //3.设置客户端字符集
    if (mysql_set_character_set(mysql, "utf8") != 0)
    {
        std::cout << "set client character failed, " << mysql_error(mysql) << std::endl;
        mysql_close(mysql);
        exit(-1);
    }
    //4.选择要操作的数据库
    //mysql_select_db(mysql, DB_NAME);    
    //5.执行sql语句
    //const char* sql = "insert stu values(null, '张三', 18, 53, 68, 87);";
    //const char* sql = "update stu set ch=ch+30 where sn=1";
    //const char* sql = "delete from stu where sn=1";
    const char* sql = "select * from stu;";
    if (mysql_query(mysql, sql) != 0)
    {
        std::cout << "mysql query failed, " << mysql_error(mysql) << std::endl;
        mysql_close(mysql);
        exit(-1);
    }
    //if execute find
    //6.保存查找结果到本地
    MYSQL_RES* res = mysql_store_result(mysql);
    if (res == nullptr)
    {
        std::cout << "store result failed" << std::endl;
        exit(-1);
    }
    //7.获取结果集中的结果条数
    int row_num = mysql_num_rows(res);
    int col_num = mysql_num_fields(res);
    //8.遍历保存到本地的结果集
    for (int i = 0; i < row_num; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for (int j = 0; j < col_num; j++)
        {
            std::cout << row[j] << "\t";
        }
        std::cout << std::endl;
    }
    //9.释放结果集
    mysql_free_result(res);
    //10.关闭连接释放句柄
    mysql_close(mysql);
    return 0;
}